<template>
  <div class="requestPresentList">
    <x-header class="header" :left-options="{showBack: showHeaderBack}" ref="header">赠送请求审批列表</x-header>
    <div class="topHolder"></div>
    <div class="searchArea" ref="searchArea">
      <search v-if="loadingStatus" position="absolute" top="46px" v-model="search" class="disabled" placeholder="搜索赠送人"></search>
      <search v-else position="absolute" top="46px" v-model="search" @on-submit="refreshList()" @on-clear="refreshList()" @on-cancel="refreshList()" ref="search" placeholder="搜索赠送人"></search>
    </div>
    <box gap="1rem 0.8rem">
      <div class="filterArea" ref="filterArea">
        <div class="filterItem">状态：<x-button @click.native="showPresentStatus = true" type="default" v-html="$refs.presentStatus&&$refs.presentStatus.getNameValues()+'<i class=\'iconfont icon-xiangxia2\'></i>'" :show-loading="loadingStatus" :disabled="loadingStatus" class="inlineBtn popPickerBtn"></x-button></div>
      </div>
      <popup-picker @on-change="refreshList()" :show.sync="showPresentStatus" :show-cell="false" :data="presentStatus" :columns="1" v-model="choosenPresentStatus" ref="presentStatus" class="btn_popup-picker"></popup-picker>
    </box>
    <scroller :height="scrollerHeight" lock-x use-pulldown use-pullup :pulldown-config="pulldownDefaultConfig" @on-pulldown-loading="refreshList()" :pullup-config="pullupDefaultConfig" @on-pullup-loading="loadMoreList" ref="loadMoreScroller" >
      <div class="askForPresentList">
        <a v-for="(item,index) in askForPresentList" :key="index" @click="toDetail(item.PRESENT_ID)">
          <form-preview class="formPreviewList label" :class="[getStateClass(item.STATE)]" :header-label="'赠送类型：' + getType(item.TYPE)" :header-value="getState(item.STATE)" :body-items="getBody(item)"></form-preview>
        </a>
        <div class="listNoItem" v-if="askForPresentList.length <= 0">暂无赠送请求</div>
      </div>
    </scroller>
  </div>
</template>

<script>
  import {Box, XButton, PopupPicker, Scroller, FormPreview, Search } from 'vux'
  import {getRequestPresentIdList,getPresentByIds} from "../../api";
  import {message} from "../../common/util";

  export default {
    name:'requestPresentList',
    data(){
      return{
        showHeaderBack:this.GLOBAL.showHeaderBack,
        loadingStatus:false,
        search:'',
        choosenPresentStatus:['0'],
        showPresentStatus:false,
        presentStatus:[
          {name: '所有状态',value: 'all'},
          {name: '待赠送',value: '0'},
          {name: '同意赠送',value: '1'},
          {name: '不同意赠送',value: '2'}
        ],
        askForPresentList:[],
        idArrayList:[],
        scrollerHeight:'',
        pulldownDefaultConfig:{
          content: '下拉刷新',
          height: 40,
          autoRefresh: false,
          downContent: '下拉刷新',
          upContent: '释放后刷新',
          loadingContent: '正在刷新...',
          clsPrefix: 'xs-plugin-pulldown-'
        },
        pullupDefaultConfig:{
          content: '上拉加载更多',
          pullUpHeight: 60,
          height: 40,
          autoRefresh: false,
          downContent: '释放后加载',
          upContent: '上拉加载更多',
          loadingContent: '加载中...',
          clsPrefix: 'xs-plugin-pullup-'
        },
        currentPage: 0,
        totalItems:0,
        pageSize:8,
        onFetching:true
      }
    },
    components:{
      Box,
      XButton,
      PopupPicker,
      Scroller,
      FormPreview,
      Search
    },
    computed:{
      authority(){
        return this.$store.getters.getAuthorityNotice
      }
    },
    methods:{
      refreshList(params){
        this.loadingStatus = true
        this.askForPresentList = []
        this.currentPage = 0
        let reqParams = {
          choosenPresentStatus:this.choosenPresentStatus,
          search: this.search,
          authority: this.authority.present
        }
        getRequestPresentIdList(reqParams).then((res)=>{
          if(res.status == 'success'){
            this.$nextTick(() => {
              if(this.$refs.loadMoreScroller) {
                this.$refs.loadMoreScroller.reset({top: 0})
                this.$refs.loadMoreScroller.donePulldown()
              }
              this.idArrayList = res.data
              let unAuditCount = 0
              for(let item of this.idArrayList){
                if(item.STATE == 0) unAuditCount++
              }
              this.$store.commit('updateNotifyItem',{type:'presentNotice',count:unAuditCount})
              this.totalItems = res.data.length
              this.loadMoreList({callback:(params && params.callback)?params.callback:null})
            })
          }else if(res.status == 'error') {
            message({message:res.msg,type:'error'})
            console.log('getRequestPresentIdList error info:', res.msg)
          }
        }).catch((err)=>{console.log('getRequestPresentIdList catch info:',err)})
      },
      loadMoreList(params){
        if (this.onFetching) {
          this.onFetching = false
          setTimeout(() => {
            let reqParams = [],start = this.currentPage*this.pageSize,end = start + this.pageSize - 1
            for(var i = start; i <= end; i++){
              if(this.idArrayList[i] != undefined)reqParams.push(this.idArrayList[i])
            }
            getPresentByIds(reqParams).then((res)=>{
              if(res.status == 'success'){
                if(res.data.length > 0){//后端实际用这个
                  //if (this.askForPresentList.length < this.totalItems) {//前端测试用这个
                  for(var i = 0; i < res.data.length; i++){
                    this.askForPresentList.push(res.data[i])
                  }
                  this.currentPage++
                }else{
                  message({message:'已经加载到底了！',type:'info'})
                }
                this.onFetching = true
                this.$nextTick(() => {
                  if(this.$refs.loadMoreScroller != undefined){
                    this.$refs.loadMoreScroller.donePullup()
                    this.$refs.loadMoreScroller.reset()
                  }
                })
              }else if(res.status == 'error') {
                message({message:res.msg,type:'error'})
                console.log('getPresentByIds error info:', res.msg)
              }
              this.setSize()
              this.loadingStatus = false
              if(params && params.callback && typeof params.callback == 'function')params.callback()
            }).catch((err)=>{console.log('getPresentByIds catch info:',err)})
          }, 1)
        }
      },
      setSize(){
        let outHeight = 0
        if(this.$refs.header)
          outHeight = this.$refs.header.$el.offsetHeight + this.$refs.searchArea.offsetHeight + this.$refs.filterArea.offsetHeight
        let contentHeight = window.screen.height - outHeight - 150
        this.scrollerHeight = contentHeight + 'px'
      },
      getState(state){
        switch (state) {
          case 0:return '待赠送';break
          case 1:return '同意赠送';break
          case 2:return '不同意赠送';break
          default:return '无状态';break
        }
      },
      getStateClass(state){
        switch (state) {
          case 0:return 'red';break
          case 1:return 'black';break
          case 2:return 'black';break
          case 4:return 'black';break
          default:return 'gray';break
        }
      },
      getType(type){
        switch (type) {
          case 0:return '售卖库存';break
          case 1:return '存酒库存';break
          case 2:return '过期酒水';break
          case 3:return '美女台赠送';break
          case 4:return '会员卡赠送';break
          default:return '无类型';break
        }
      },
      getBody(item){
        let list = []
        if(item.MEMBERCARDUSER_ID == null && item.MEMBERCARDUSER_ID == undefined)list.push({label:'发起赠送人',value:item.PRESENTER + ' - ' + item.present_DEPARTMENT})
        else list.push({label:'会员卡办卡/充值赠送',value:''})
        list.push({label:'请求时间',value:item.REQUEST_DATETIME})
        list.push({label:'点击查看详情>>',value:''})
        return list
      },
      toDetail(id){
        this.$router.push({name:'赠送请求审批详情',params:{presentId:id}})
      }
    },
    mounted(){
      if(this.authority.present == 'present_audit' || this.authority.present == 'present_audit_all'){
        this.refreshList({callback:()=>{
            window.onresize = ()=>{
              this.setSize()
            }
          }})
        this.$store.commit('updateLoadingStatus',{isLoading:false})
      }else{
        message({message:'没有权限查看该页面',type:'error'})
        this.$router.push({path:'/noticeIndex'})
      }
    },
    beforeDestroy(){
      window.onresize = ()=>{}
    }
  }
</script>

<style lang="scss">
  .requestPresentList{
    .searchArea{
      height:44px;margin-bottom: 1rem;
      .disabled{
        .weui-search-bar__box{background: #eff1ef;}
      }
    }
  }
</style>
